package rpc;

import com.rabbitmq.client.*;
import constant.Constants;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * Created with IntelliJ IDEA.
 * Description：
 *
 * @author: zxj
 * @date: 2024-09-19
 * @time: 11:48:23
 */
public class RPCServer {
    public static void main(String[] args) throws IOException, TimeoutException {
        // 1. 创建 channel
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(Constants.HOST);
        factory.setPort(Constants.PORT);
        factory.setVirtualHost(Constants.VIRTUAL_HOST);
        factory.setUsername(Constants.USERNAME);
        factory.setPassword(Constants.PASSWORD);
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        // 2. 声明队列
        channel.queueDeclare(Constants.RPC_REQUEST_QUEUE_NAME, true, false, false, null);

        // 3. 接受消息并消费
        channel.basicQos(1); // 设置同时最多只能获取⼀个消息
        System.out.println("Awaiting RPC request");
        DefaultConsumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                AMQP.BasicProperties basicProperties = new AMQP.BasicProperties()
                        .builder()
                        .correlationId(properties.getCorrelationId())
                        .build();
                // 业务处理
                String message = new String(body);
                String response = "request:" + message + ", response: " + "处理成功";
                // 回复消息
                channel.basicPublish("", properties.getReplyTo(), basicProperties, response.getBytes());
                // 对消息进行应答
                channel.basicAck(envelope.getDeliveryTag(), false);
            }
        };

        channel.basicConsume(Constants.RPC_REQUEST_QUEUE_NAME, false, consumer);
    }
}
